package com.dlc.beijingrfid.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;

import com.dlc.commonlibrary.ble.BleConstant;
import com.dlc.commonlibrary.ble.BleHelper;
import com.dlc.commonlibrary.ble.RfidHelper;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.net.bean.OrderDetailBean;
import com.dlc.beijingrfid.net.protocol.MyProto;
import com.trello.rxlifecycle.android.ActivityEvent;
import java.util.ArrayList;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class RukuActivity extends BaseActivity {
    @BindView(R.id.titleBar) TitleBar titleBar;
    @BindView(R.id.order_number) TextView mOrderNumber;
    @BindView(R.id.hotel) TextView mHotel;
    @BindView(R.id.pro_name) TextView mProName;
    @BindView(R.id.classify) TextView mClassify;
    @BindView(R.id.pro_count) TextView mProCount;

    private String ordernoData;
    private StringBuilder mStringBuilder;
    private DoResultDialog doReadDialog,doResultDialog;
    private Handler mHandler;
    private OrderDetailBean.DataBean mOrderData;
    private String[] mOrderRfids;

    @Override
    protected int getLayoutID() {
        return R.layout.activity_chuku;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ordernoData = getIntent().getStringExtra("orderno");

        titleBar.leftExit(this);
        titleBar.titleText.setText("入库");

        mHandler = new Handler();

        // 查询送货单详情
        queryOrderDetail();
        doReadRFID();
        doResult();
    }

    /**
     * 查询订单详情
     */
    private void queryOrderDetail() {
        MyProto.get()
            .OrderDetailByOrderNo(ordernoData)
            .compose(this.<OrderDetailBean.DataBean>bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(new Subscriber<OrderDetailBean.DataBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                }

                @Override
                public void onNext(OrderDetailBean.DataBean dataBean) {

                    // 缓存一下订单详情
                    mOrderData = dataBean;

                    mOrderNumber.setText(dataBean.orderno);
                    mHotel.setText(dataBean.hotel);
                    mOrderRfids = dataBean.rfids.split(",");

                    if (dataBean.spec_group != null
                        && dataBean.spec_group.size() > 0
                        && dataBean.spec_group.get(0) != null) {

                        OrderDetailBean.DataBean.SpecGroupBean specGroupBean =
                            dataBean.spec_group.get(0);
                        mProName.setText(specGroupBean.title);
                        mClassify.setText(specGroupBean.spec);
                        mProCount.setText(dataBean.nums);
                    }
                }
            });
    }
    private void doReadRFID() {
        doReadDialog =
                DoResultDialog.newDialog(this).
                        setWorkingText(getString(R.string.read_rfid_ing))
                        .setSuccessImage(R.mipmap.ic_success)
                        .setSuccessText(getString(R.string.scan_over))
                        .setButton("完成扫描", new DoResultDialog.OnClickButtonListener() {
                            @Override
                            public void onClickButton(DoResultDialog dialog) {

                                BleHelper.getInstance().write(BleConstant.API_END_READ);
                                //如果1秒钟内，没有接到停止读取命令，就认为是蓝牙断开
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (isBleStop ) {
                                            if (mStringBuilder.length() > 0) {
                                                doReadDialog.dismiss();
                                                judgeData(false);
                                            }
                                        }
                                    }
                                },1000);
                            }
                        });

        doReadDialog.setCancelable(false);

    }

    private void doResult() {

        doResultDialog = DoResultDialog.newDialog(this)
                .setWorkingText(getString(R.string.commit_counting_result))
                .setSuccessImage(R.mipmap.ic_success)
                .setSuccessText(getString(R.string.commit_counting_result_success));

        doResultDialog.setCancelable(false);


    }

    /**
     * 读取RFID
     */
    private String startData = "";
    private boolean isBleStop = true;//蓝牙是否已断开
    public void checkRFID() {

        if (mOrderData == null) {
            showToast("未获得订单数据");
            return;
        }

        mStringBuilder = new StringBuilder();
        mStringBuilder.delete(0, mStringBuilder.length());

        if (BleHelper.getInstance().getConnectDevice() != null) { //已经连接了

            showToast("正在读取中.....");
            isBleStop = true;
            doReadDialog.showWorking(true);

            BleHelper.getInstance().startReadDevice(BleConstant.height_pwd);
            BleHelper.getInstance().readValue(new BleHelper.BleCallBack() { //扫描完已定调用stopReadValue
                @Override
                public void readDatas(String data) {

                    LogPlus.e("BLE", "data:" + data);
                    data = data.replaceAll("\r|\n| ", "");
                    mStringBuilder.append(data);
                    if (mStringBuilder.length() > 5) {
                        startData = mStringBuilder.substring(mStringBuilder.length() - 2, mStringBuilder.length());
                        LogPlus.e("BLE", "startData:" + startData);
                    }
                    if (startData.contains(BleConstant.API_STOP_READ)) {
                        isBleStop = false;
                        if (mStringBuilder.length() > 0) {
                            doReadDialog.dismiss();
                            judgeData(true);
                        }
                    }
                }
            });
        } else { //跳去连接页面
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("type", "2");
            startActivity(intent);
            finish();
        }
    }
    private void judgeData(final boolean isStop) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                String data = mStringBuilder.toString();
                ArrayList<String> rfids = RfidHelper.exportRFIDs(data);

                if (isStop) {
                    if (rfids.size() > 0) {
                        doResultDialog.showResultAndDismiss(true, 1000);
                        doResultDialog.dismiss();

                        ArrayList<String> diffRfids = new ArrayList<>();
                        for (int i = 0; i < mOrderRfids.length; i++) {
                            if (!data.contains(mOrderRfids[i])) {
                                diffRfids.add(mOrderRfids[i]);
                            }
                        }

                        Intent intent = new Intent(RukuActivity.this, RuKuDetailActivity.class);
                        intent.putExtra("orderno", ordernoData);
                        intent.putExtra("hotel", mProName.getText().toString());
                        intent.putExtra("spec", mClassify.getText().toString());
                        intent.putExtra("count", mProCount.getText().toString());
                        intent.putExtra("diff", diffRfids);

                        startActivity(intent);
                    } else {
                        doResultDialog.setFailedText("读取不到RFID");
                        doResultDialog.setFailedImage(R.mipmap.ic_error);
                        doResultDialog.showResultAndDismiss(false, 2000);
                    }
                }else {
                    //跳去连接页面
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showToast("蓝牙已断开，跳到连接页面");
                            Intent intent = new Intent(getActivity(),MainActivity.class);
                            intent.putExtra("type", "2");
                            startActivity(intent);
                        }
                    },500);
                }
            }
        });

        //00013B7B35FF,00013B7B24D4,00013B7B1BBE,00013B7B4BEA,00013B7B3AC2

    }


    @OnClick({ R.id.check })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check:
                checkRFID();
                break;
        }
    }
}
//#	Result	Protocol	Host	URL	Body	Caching	Content-Type	Process	Comments	Custom
//30	200	HTTP	jingnuo.abu.green	/user_api/wash_record?userid=33&timestamp=1536287781&sign=3acea60b674716ca0bb30d926d793e04	136	no-store, no-cache, must-revalidate, post-check=0, pre-check=0; Expires: Thu, 19 Nov 1981 08:52:00 GMT	text/html; charset=UTF-8